<?php

namespace App\Http\Controllers\Admin\Finance\Payable;

use App\Http\Controllers\Controller;
use App\Models\finance\PayableDeliveryRegistrationModel;
use App\Models\OrderModel;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;

class DeliveryRegistration extends Controller
{
    /**
     * 提货送货登记费列表
     */
    public function list(Request $request)
    {
        $date_start = $request->input('date_start', '');
        $date_end = $request->input('date_end', '');
        $agent_id = $request->input('agent_id', 0);
        $order_sn = $request->input('order_sn', '');
        $project_type = $request->input('project_type', 0);
        $status = $request->input('status', 0);
        $page = $request->input('page', 1);
        $limit = $request->input('limit', 20);

        $query = PayableDeliveryRegistrationModel::with(['createAdmin', 'agent', 'order']);

        if ($date_start && $date_end) {
            $query->whereBetween('date', [$date_start, $date_end]);
        }

        if ($agent_id) {
            $query->where('agent_id', $agent_id);
        }

        if ($order_sn) {
            $query->whereHas('order', function ($query) use ($order_sn) {
                $query->where('sn', 'like', "%{$order_sn}%");
            });
        }

        if ($project_type) {
            $query->where('project_type', $project_type);
        }

        if ($status) {
            $query->where('status', $status);
        }

        $total = $query->count();
        $items = $query->orderBy('id', 'desc')
            ->offset(($page - 1) * $limit)
            ->limit($limit)
            ->get()
            ->map(function($item) {
                return [
                    'id' => $item->id,
                    'agent_id' => $item->agent_id,
                    'agent_name' => $item->agent->name ?? '',
                    'date' => $item->date,
                    'order_id' => $item->order_id,
                    'order_sn' => $item->order->sn ?? '',
                    'project_type' => $item->project_type,
                    'project_type_name' => PayableDeliveryRegistrationModel::PROJECT_TYPE_LIST[$item->project_type] ?? '',
                    'weight' => $item->weight,
                    'amount' => $item->amount,
                    'registration_fee' => $item->registration_fee,
                    'parking_fee' => $item->parking_fee,
                    'tunnel_fee' => $item->tunnel_fee,
                    'bridge_fee' => $item->bridge_fee,
                    'scanning_fee' => $item->scanning_fee,
                    'other_fee' => $item->other_fee,
                    'total_amount' => $item->total_amount,
                    'remarks' => $item->remarks,
                    'status' => $item->status,
                    'status_name' => PayableDeliveryRegistrationModel::STATUS_LIST[$item->status] ?? '',
                    'pay_amount' => $item->pay_amount,
                    'created_admin_id' => $item->created_admin_id,
                    'created_admin_name' => $item->createAdmin->name ?? '',
                    'created_at' => $item->created_at->format('Y-m-d H:i:s')
                ];
            });

        // 计算总金额
        $totalAmount = $query->sum('total_amount');

        return $this->success([
            'list' => $items,
            'total' => $total,
        ]);
    }

    /**
     * 添加提货送货登记费记录
     */
    public function add(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'agent_id' => 'required|integer|min:1',
            'date' => 'required|date',
            'order_sn' => 'required|string',
            'project_type' => 'required|integer|in:1,2,3',
            'weight' => 'required|numeric|min:0',
            'amount' => 'required|numeric|min:0',
            'registration_fee' => 'numeric|min:0',
            'parking_fee' => 'numeric|min:0',
            'tunnel_fee' => 'numeric|min:0',
            'bridge_fee' => 'numeric|min:0',
            'scanning_fee' => 'numeric|min:0',
            'other_fee' => 'numeric|min:0',
        ]);

        if ($validator->fails()) {
            return $this->error($validator->errors()->first());
        }

        // 验证入仓单是否存在
        $order = OrderModel::where('sn', $request->input('order_sn'))->first();
        if (!$order) {
            return $this->error('入仓单不存在');
        }

        try {
            // 获取各项费用
            $amount = $request->input('amount');
            $registrationFee = $request->input('registration_fee', 0);
            $parkingFee = $request->input('parking_fee', 0);
            $tunnelFee = $request->input('tunnel_fee', 0);
            $bridgeFee = $request->input('bridge_fee', 0);
            $scanningFee = $request->input('scanning_fee', 0);
            $otherFee = $request->input('other_fee', 0);
            
            // 计算合计金额
            $totalAmount = $amount + $registrationFee + $parkingFee + $tunnelFee + 
                           $bridgeFee + $scanningFee + $otherFee;

            $registration = new PayableDeliveryRegistrationModel();
            $registration->agent_id = $request->input('agent_id');
            $registration->date = $request->input('date');
            $registration->order_id = $order->id;
            $registration->project_type = $request->input('project_type');
            $registration->weight = $request->input('weight');
            $registration->amount = $amount;
            $registration->registration_fee = $registrationFee;
            $registration->parking_fee = $parkingFee;
            $registration->tunnel_fee = $tunnelFee;
            $registration->bridge_fee = $bridgeFee;
            $registration->scanning_fee = $scanningFee;
            $registration->other_fee = $otherFee;
            $registration->total_amount = $totalAmount;
            $registration->remarks = trim($request->input('remarks', ''));
            $registration->status = PayableDeliveryRegistrationModel::STATUS_UNPAID;
            $registration->pay_amount = 0;
            $registration->created_admin_id = $request->get('auth')->id;
            $registration->save();

            return $this->success($registration);
        } catch (\Exception $e) {
            return $this->error('添加失败：' . $e->getMessage());
        }
    }

    /**
     * 更新提货送货登记费记录
     */
    public function update(Request $request, $id)
    {
        $registration = PayableDeliveryRegistrationModel::find($id);
        if (!$registration) {
            return $this->error('提货送货登记费记录不存在');
        }

        $validator = Validator::make($request->all(), [
            'agent_id' => 'required|integer|min:1',
            'date' => 'required|date',
            'order_sn' => 'required|string',
            'project_type' => 'required|integer|in:1,2,3',
            'weight' => 'required|numeric|min:0',
            'amount' => 'required|numeric|min:0',
            'registration_fee' => 'numeric|min:0',
            'parking_fee' => 'numeric|min:0',
            'tunnel_fee' => 'numeric|min:0',
            'bridge_fee' => 'numeric|min:0',
            'scanning_fee' => 'numeric|min:0',
            'other_fee' => 'numeric|min:0',
        ]);

        if ($validator->fails()) {
            return $this->error($validator->errors()->first());
        }

        // 验证入仓单是否存在
        $order = OrderModel::where('sn', $request->input('order_sn'))->first();
        if (!$order) {
            return $this->error('入仓单不存在');
        }

        try {
            // 获取各项费用
            $amount = $request->input('amount');
            $registrationFee = $request->input('registration_fee', 0);
            $parkingFee = $request->input('parking_fee', 0);
            $tunnelFee = $request->input('tunnel_fee', 0);
            $bridgeFee = $request->input('bridge_fee', 0);
            $scanningFee = $request->input('scanning_fee', 0);
            $otherFee = $request->input('other_fee', 0);
            
            // 计算合计金额
            $totalAmount = $amount + $registrationFee + $parkingFee + $tunnelFee + 
                           $bridgeFee + $scanningFee + $otherFee;

            $registration->agent_id = $request->input('agent_id');
            $registration->date = $request->input('date');
            $registration->order_id = $order->id;
            $registration->project_type = $request->input('project_type');
            $registration->weight = $request->input('weight');
            $registration->amount = $amount;
            $registration->registration_fee = $registrationFee;
            $registration->parking_fee = $parkingFee;
            $registration->tunnel_fee = $tunnelFee;
            $registration->bridge_fee = $bridgeFee;
            $registration->scanning_fee = $scanningFee;
            $registration->other_fee = $otherFee;
            $registration->total_amount = $totalAmount;
            $registration->remarks = trim($request->input('remarks', ''));
            $registration->save();

            return $this->success($registration);
        } catch (\Exception $e) {
            return $this->error('更新失败：' . $e->getMessage());
        }
    }

    /**
     * 删除提货送货登记费记录
     */
    public function delete($id)
    {
        $registration = PayableDeliveryRegistrationModel::find($id);
        if (!$registration) {
            return $this->error('提货送货登记费记录不存在');
        }

        if ($registration->status != PayableDeliveryRegistrationModel::STATUS_UNPAID) {
            return $this->error('已付款的记录不能删除');
        }

        try {
            $registration->delete();
            return $this->success(true);
        } catch (\Exception $e) {
            return $this->error('删除失败：' . $e->getMessage());
        }
    }

    /**
     * 获取提货送货登记费详情
     */
    public function detail($id)
    {
        $registration = PayableDeliveryRegistrationModel::with(['createAdmin', 'agent', 'order'])->find($id);
        if (!$registration) {
            return $this->error('提货送货登记费记录不存在');
        }

        $data = $registration->toArray();
        $data['agent_name'] = $registration->agent->name ?? '';
        $data['order_sn'] = $registration->order->sn ?? '';
        $data['project_type_name'] = PayableDeliveryRegistrationModel::PROJECT_TYPE_LIST[$registration->project_type] ?? '';
        $data['status_name'] = PayableDeliveryRegistrationModel::STATUS_LIST[$registration->status] ?? '';
        $data['created_admin_name'] = $registration->createAdmin->name ?? '';

        return $this->success($data);
    }

    /**
     * 设置付款状态
     */
    public function setPaid(Request $request, $id)
    {
        $registration = PayableDeliveryRegistrationModel::find($id);
        if (!$registration) {
            return $this->error('提货送货登记费记录不存在');
        }

        $validator = Validator::make($request->all(), [
            'pay_amount' => 'required|numeric|min:0',
        ]);

        if ($validator->fails()) {
            return $this->error($validator->errors()->first());
        }

        $payAmount = $request->input('pay_amount');
        $totalAmount = $registration->total_amount;

        // 设置付款状态
        if ($payAmount >= $totalAmount) {
            $status = PayableDeliveryRegistrationModel::STATUS_PAID;
            $payAmount = $totalAmount; // 确保支付金额不超过总金额
        } elseif ($payAmount > 0) {
            $status = PayableDeliveryRegistrationModel::STATUS_PART_PAID;
        } else {
            $status = PayableDeliveryRegistrationModel::STATUS_UNPAID;
        }

        try {
            $registration->pay_amount = $payAmount;
            $registration->status = $status;
            $registration->save();

            return $this->success($registration);
        } catch (\Exception $e) {
            return $this->error('设置付款状态失败：' . $e->getMessage());
        }
    }
} 